package com.learning.platform.service;

import com.learning.platform.entity.UserLearningContext;
import com.learning.platform.enums.QueryIntent;
import com.learning.platform.repository.UserLearningContextRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 用户学习上下文服务
 * 管理用户的学习状态、偏好和历史记录
 */
@Service
@Transactional
public class UserContextService {
    
    @Autowired
    private UserLearningContextRepository contextRepository;
    
    /**
     * 获取或创建用户学习上下文
     */
    public UserLearningContext getOrCreateContext(Long userId) {
        return contextRepository.findByUserId(userId)
            .orElseGet(() -> createDefaultContext(userId));
    }
    
    /**
     * 创建默认的学习上下文
     */
    private UserLearningContext createDefaultContext(Long userId) {
        UserLearningContext context = new UserLearningContext(userId);
        context.setRecentTopics(new ArrayList<>());
        context.setLearningPreferences(createDefaultPreferences());
        context.setConversationHistory(new ArrayList<>());
        context.setWeakAreas(new ArrayList<>());
        context.setStrongAreas(new ArrayList<>());
        
        return contextRepository.save(context);
    }
    
    /**
     * 创建默认学习偏好
     */
    private Map<String, Object> createDefaultPreferences() {
        Map<String, Object> preferences = new HashMap<>();
        preferences.put("explanationStyle", "详细"); // 详细、简洁、实例导向
        preferences.put("codeExamples", true);
        preferences.put("interactiveMode", true);
        preferences.put("difficultyPreference", "渐进式");
        preferences.put("feedbackFrequency", "实时");
        return preferences;
    }
    
    /**
     * 更新用户查询记录
     */
    public void updateQueryRecord(Long userId, String query, QueryIntent intent) {
        UserLearningContext context = getOrCreateContext(userId);
        
        // 更新提问统计
        context.setTotalQuestionsAsked(context.getTotalQuestionsAsked() + 1);
        if (intent.isProgrammingRelated()) {
            context.setProgrammingQuestionsAsked(context.getProgrammingQuestionsAsked() + 1);
        }
        
        // 更新对话历史
        updateConversationHistory(context, query, intent);
        
        // 更新最近话题
        updateRecentTopics(context, intent);
        
        // 分析并更新技能水平
        updateSkillLevel(context);
        
        contextRepository.save(context);
    }
    
    /**
     * 更新对话历史
     */
    private void updateConversationHistory(UserLearningContext context, String query, QueryIntent intent) {
        List<UserLearningContext.ConversationEntry> history = context.getConversationHistory();
        if (history == null) {
            history = new ArrayList<>();
        }
        
        // 添加新的对话条目
        UserLearningContext.ConversationEntry entry = new UserLearningContext.ConversationEntry(
            query, intent.name(), context.getCurrentLanguage(), extractTopic(query, intent)
        );
        history.add(entry);
        
        // 保持历史记录在合理范围内（最近50条）
        if (history.size() > 50) {
            history = history.subList(history.size() - 50, history.size());
        }
        
        context.setConversationHistory(history);
    }
    
    /**
     * 更新最近话题
     */
    private void updateRecentTopics(UserLearningContext context, QueryIntent intent) {
        List<String> recentTopics = context.getRecentTopics();
        if (recentTopics == null) {
            recentTopics = new ArrayList<>();
        }
        
        String topic = intent.getDisplayName();
        
        // 移除已存在的相同话题
        recentTopics.remove(topic);
        
        // 添加到开头
        recentTopics.add(0, topic);
        
        // 保持最近10个话题
        if (recentTopics.size() > 10) {
            recentTopics = recentTopics.subList(0, 10);
        }
        
        context.setRecentTopics(recentTopics);
    }
    
    /**
     * 从查询中提取话题
     */
    private String extractTopic(String query, QueryIntent intent) {
        // 简化的话题提取逻辑
        String lowerQuery = query.toLowerCase();
        
        // 编程语言识别
        if (lowerQuery.contains("java")) return "Java";
        if (lowerQuery.contains("python")) return "Python";
        if (lowerQuery.contains("javascript")) return "JavaScript";
        if (lowerQuery.contains("react")) return "React";
        if (lowerQuery.contains("vue")) return "Vue.js";
        if (lowerQuery.contains("spring")) return "Spring";
        if (lowerQuery.contains("mysql")) return "MySQL";
        if (lowerQuery.contains("算法")) return "算法";
        if (lowerQuery.contains("数据结构")) return "数据结构";
        
        return intent.getDisplayName();
    }
    
    /**
     * 更新技能水平
     */
    private void updateSkillLevel(UserLearningContext context) {
        int totalQuestions = context.getTotalQuestionsAsked();
        int programmingQuestions = context.getProgrammingQuestionsAsked();
        
        // 基于提问数量和类型简单评估技能水平
        String currentLevel = context.getSkillLevel();
        String newLevel = calculateSkillLevel(totalQuestions, programmingQuestions, currentLevel);
        
        if (!newLevel.equals(currentLevel)) {
            context.setSkillLevel(newLevel);
        }
    }
    
    /**
     * 计算技能水平
     */
    private String calculateSkillLevel(int totalQuestions, int programmingQuestions, String currentLevel) {
        // 简化的技能水平计算逻辑
        if (programmingQuestions >= 100) return "EXPERT";
        if (programmingQuestions >= 50) return "ADVANCED";
        if (programmingQuestions >= 20) return "INTERMEDIATE";
        return "BEGINNER";
    }
    
    /**
     * 更新当前学习语言
     */
    public void updateCurrentLanguage(Long userId, String language) {
        UserLearningContext context = getOrCreateContext(userId);
        context.setCurrentLanguage(language);
        contextRepository.save(context);
    }
    
    /**
     * 更新学习目标
     */
    public void updateLearningGoals(Long userId, String goals) {
        UserLearningContext context = getOrCreateContext(userId);
        context.setLearningGoals(goals);
        contextRepository.save(context);
    }
    
    /**
     * 添加薄弱环节
     */
    public void addWeakArea(Long userId, String area) {
        UserLearningContext context = getOrCreateContext(userId);
        List<String> weakAreas = context.getWeakAreas();
        if (weakAreas == null) {
            weakAreas = new ArrayList<>();
        }
        
        if (!weakAreas.contains(area)) {
            weakAreas.add(area);
            context.setWeakAreas(weakAreas);
            contextRepository.save(context);
        }
    }
    
    /**
     * 添加优势领域
     */
    public void addStrongArea(Long userId, String area) {
        UserLearningContext context = getOrCreateContext(userId);
        List<String> strongAreas = context.getStrongAreas();
        if (strongAreas == null) {
            strongAreas = new ArrayList<>();
        }
        
        if (!strongAreas.contains(area)) {
            strongAreas.add(area);
            context.setStrongAreas(strongAreas);
            contextRepository.save(context);
        }
    }
    
    /**
     * 获取用户学习统计
     */
    public UserLearningStats getUserStats(Long userId) {
        UserLearningContext context = getOrCreateContext(userId);
        
        return UserLearningStats.builder()
            .totalQuestions(context.getTotalQuestionsAsked())
            .programmingQuestions(context.getProgrammingQuestionsAsked())
            .skillLevel(context.getSkillLevel())
            .currentLanguage(context.getCurrentLanguage())
            .recentTopics(context.getRecentTopics())
            .weakAreas(context.getWeakAreas())
            .strongAreas(context.getStrongAreas())
            .lastActiveAt(context.getLastActiveAt())
            .build();
    }
    
    /**
     * 用户学习统计数据
     */
    public static class UserLearningStats {
        private Integer totalQuestions;
        private Integer programmingQuestions;
        private String skillLevel;
        private String currentLanguage;
        private List<String> recentTopics;
        private List<String> weakAreas;
        private List<String> strongAreas;
        private LocalDateTime lastActiveAt;
        
        public static Builder builder() {
            return new Builder();
        }
        
        // Getters
        public Integer getTotalQuestions() { return totalQuestions; }
        public Integer getProgrammingQuestions() { return programmingQuestions; }
        public String getSkillLevel() { return skillLevel; }
        public String getCurrentLanguage() { return currentLanguage; }
        public List<String> getRecentTopics() { return recentTopics; }
        public List<String> getWeakAreas() { return weakAreas; }
        public List<String> getStrongAreas() { return strongAreas; }
        public LocalDateTime getLastActiveAt() { return lastActiveAt; }
        
        public static class Builder {
            private UserLearningStats stats = new UserLearningStats();
            
            public Builder totalQuestions(Integer totalQuestions) {
                stats.totalQuestions = totalQuestions;
                return this;
            }
            
            public Builder programmingQuestions(Integer programmingQuestions) {
                stats.programmingQuestions = programmingQuestions;
                return this;
            }
            
            public Builder skillLevel(String skillLevel) {
                stats.skillLevel = skillLevel;
                return this;
            }
            
            public Builder currentLanguage(String currentLanguage) {
                stats.currentLanguage = currentLanguage;
                return this;
            }
            
            public Builder recentTopics(List<String> recentTopics) {
                stats.recentTopics = recentTopics;
                return this;
            }
            
            public Builder weakAreas(List<String> weakAreas) {
                stats.weakAreas = weakAreas;
                return this;
            }
            
            public Builder strongAreas(List<String> strongAreas) {
                stats.strongAreas = strongAreas;
                return this;
            }
            
            public Builder lastActiveAt(LocalDateTime lastActiveAt) {
                stats.lastActiveAt = lastActiveAt;
                return this;
            }
            
            public UserLearningStats build() {
                return stats;
            }
        }
    }
}


